# -*-coding:utf-8-*-

import tensorflow as tf
from numpy.random import RandomState

'''
神经网络过程：
1. 定义网络结构和前向传播的结果
2. 定义损失函数及反向传播优化算法
3. 生成回话，并在训练数据上反复运行反向传播算法
'''
# 定义训练集batch大小
batch_size = 8

# stddev= 标准差, 定义权重, 采用两层网络结构
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))

# 特征值，采用占位符处理
feature = tf.placeholder(tf.float32, shape=(None, 2), name='x_input')
y_ = tf.placeholder(tf.float32, shape=(None, 1), name='y_input')

a = tf.matmul(feature, w1)
y = tf.matmul(a, w2)

# 定义损失函数及反向传播算法

# 交叉熵
cross_entropy = -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)))
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)

# 随机数生产模拟数据集
random = RandomState(1)
dataset_size = 128

input_feature_data = random.rand(dataset_size, 2)

# 设置样本demo。 x1 + x2 < 1 的为正品
sample = [[int(x1 + x2 < 1)] for x1, x2 in input_feature_data]
print(sample)
# 创建回话运行tf程序

with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    print(sess.run(w1))
    print(sess.run(w2))

    # 训练的轮数
    SETPS = 5000

    for i in range(SETPS):
        start = (i * batch_size) % dataset_size
        end = min(start + batch_size, dataset_size)

        sess.run(train_step, feed_dict={feature: input_feature_data[start:end], y_: sample[start:end]})

        if i % 1000 == 0:
            total_cross_entropy = sess.run(cross_entropy, feed_dict={feature: input_feature_data, y_: sample})
            print("%d steps, 交叉熵=%g" %(i, total_cross_entropy))

    print(sess.run(w1))
    print(sess.run(w2))








